package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.MathUtil;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 提币界面
 */
public class TransferTransferActivity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_available)
    TextView tvAvailable;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.tv_service_charge)
    TextView tvServiceCharge;
    @BindView(R.id.tv_remain)
    TextView tvRemain;
    @BindView(R.id.rl_confirm)
    RelativeLayout rlConfirm;

    IPresenter presenter;
    int accountType;
    @BindView(R.id.tv_available_unit)
    TextView tvAvailableUnit;
    @BindView(R.id.tv_input_unit)
    TextView tvInputUnit;
    @BindView(R.id.tv_service_charge_unit)
    TextView tvServiceChargeUnit;
    @BindView(R.id.tv_remain_unit)
    TextView tvRemainUnit;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_address_tip)
    TextView tvAddressTip;

    public static Intent createIntent(Context context, int accountType) {
        Intent intent = new Intent(context, TransferTransferActivity.class);
        intent.putExtra("accountType", accountType);
        return intent;
    }

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_transfer_transfer;
    }

    @Override
    public void initParam() {
        Intent intent = getIntent();
        accountType = intent.getIntExtra("accountType", ConstantParam.ACCOUNT_TYPE_WITH_GTE);
        presenter = new PresenterImpl(this);
    }

    @Override
    public void initView() {
        String title = "GTE";
        switch (accountType) {
            case ConstantParam.ACCOUNT_TYPE_WITH_GTE:
                tvAvailableUnit.setText("GTE");
                tvInputUnit.setText("GTE");
                tvServiceChargeUnit.setText("GTE");
                tvRemainUnit.setText("GTE");
                title = "GTE";
                tvTip.setText("最小提币数量为20个GTE，请勿向上述地址充值任何非GTE资产，否则资产将不可找回。您充值至上述地址后，需要整个网络节点的确认,15次网络确认后导致,30次网络确认后可提币。");
                tvAddressTip.setText("提币地址");
                etAddress.setHint("输入或粘贴提币地址");
                break;
            case ConstantParam.ACCOUNT_TYPE_WITH_GTK:
                tvAvailableUnit.setText("GTK");
                tvInputUnit.setText("GTK");
                tvServiceChargeUnit.setText("GTK");
                tvRemainUnit.setText("GTK");
                title = "GTK";
                tvTip.setText("");
                tvAddressTip.setText("对方GTK编号");
                etAddress.setHint("输入GTK编号地址");
                break;
        }


        initActionBar(toolbar, tvTitle, title + "提币");
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString().trim();
                try {
                    userInput = Double.valueOf(s);
                    serviceCharge = userInput * serviceChargeRate;
                    remain = userInput - serviceCharge;
                } catch (Exception e) {
                    userInput = 0;
                    serviceCharge = 0;
                    remain = 0;
                }
                tvServiceCharge.setText(String.format("%.2f", serviceCharge));
                tvRemain.setText(String.format("%.2f", remain));
            }
        });
    }

    @Override
    public void initOperator() {
        JSONObject param = new JSONObject();
        try {
            param.put("currencyType", accountType + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.transferOpenTransfer(param.toString());

        //获取自己的充币地址
//        JSONObject paramWithRecharge = new JSONObject();
//        presenter.transferRecharge(paramWithRecharge.toString());

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_transfer_transfer, menu);
        return true;
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        switch (accountType){
            case ConstantParam.ACCOUNT_TYPE_WITH_GTE:
                menu.findItem(R.id.transfer_gte).setVisible(false);
                menu.findItem(R.id.transfer_gtk).setVisible(true);
                break;
            case ConstantParam.ACCOUNT_TYPE_WITH_GTK:
                menu.findItem(R.id.transfer_gte).setVisible(true);
                menu.findItem(R.id.transfer_gtk).setVisible(false);
                break;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.transfer_gte:
                accountType = ConstantParam.ACCOUNT_TYPE_WITH_GTE;
                invalidateOptionsMenu();
                initView();
                initOperator();
                break;
            case R.id.transfer_gtk:
                accountType = ConstantParam.ACCOUNT_TYPE_WITH_GTK;
                invalidateOptionsMenu();
                initView();
                initOperator();
                break;
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }




    int REQ_CODE_WITH_DEFAULT_SCAN = 1;

    @OnClick({R.id.iv_scan, R.id.tv_all, R.id.rl_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                Intent intent = new Intent(context, CaptureActivity.class);
                startActivityForResult(intent, REQ_CODE_WITH_DEFAULT_SCAN);
                break;
            case R.id.tv_all:
                etInput.setText(availableAmount + "");
                break;
            case R.id.rl_confirm:
                if (TextUtils.isEmpty(etAddress.getText().toString().trim())) {
                    ToastUtil.getInstance().shortLength(context, "请输入提币地址");
                    return;
                }
                if (userInput <= 0) {
                    ToastUtil.getInstance().shortLength(context, "请输入提币数量");
                    return;
                }
                if (userInput > availableAmount) {
                    if (dialogWithFailTip == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                        dialogWithFailTip = builder.create();
                    }
                    dialogWithFailTip.setMessage("可用资产不足");
                    dialogWithFailTip.show();
                } else {
                    if (dialogWithPayPasswordInput == null) {
                        AlertDialog.Builder builderWithPay = new AlertDialog.Builder(context);
                        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_input_pay_password, null);
                        final EditText etPayPassword = (EditText) layout.findViewById(R.id.et_pay_password);
                        LinearLayout llDismiss = (LinearLayout) layout.findViewById(R.id.ll_dismiss);
                        TextView tvNextStep = (TextView) layout.findViewById(R.id.tv_next);
                        View.OnClickListener onClickListener = new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                switch (view.getId()) {
                                    case R.id.ll_dismiss:
                                        dialogWithPayPasswordInput.dismiss();
                                        break;
                                    case R.id.tv_next:
                                        String passwrod = etPayPassword.getText().toString();
                                        if (TextUtils.isEmpty(passwrod)) {
                                            ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                            return;
                                        }
                                        JSONObject param = new JSONObject();
                                        try {
                                            param.put("currencyType", accountType + "");
                                            param.put("recChain", etAddress.getText().toString().trim());
                                            param.put("gtkAccount", etAddress.getText().toString().trim());
                                            param.put("transferCount", userInput + "");
                                            param.put("fee", serviceCharge + "");
                                            param.put("destCount", remain + "");
                                            param.put("payPassword", passwrod + "");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        presenter.transferTransfer(param.toString());
                                        dialogWithPayPasswordInput.dismiss();
                                        break;
                                }
                            }
                        };
                        llDismiss.setOnClickListener(onClickListener);
                        tvNextStep.setOnClickListener(onClickListener);
                        dialogWithPayPasswordInput = builderWithPay.setView(layout).create();
                    }
                    dialogWithPayPasswordInput.show();
                }
                break;
        }
    }

    AlertDialog dialogWithFailTip;
    AlertDialog dialogWithPayPasswordInput;
    double availableAmount;
    double serviceChargeRate;
    double serviceCharge;
    double remain;
    double userInput;

    @Override
    public void onTransferOpenTransferSuccess(String resp) {
        super.onTransferOpenTransferSuccess(resp);
        try {
            JSONObject jsonObject = new JSONObject(resp);
            availableAmount = jsonObject.optDouble("amount");
            serviceChargeRate = jsonObject.optDouble("fee");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        tvAvailable.setText(availableAmount + "");
        String s = etInput.getText().toString().trim();
        userInput = Double.valueOf(s);
        serviceCharge = MathUtil.multiply(userInput+"", serviceChargeRate+"");
        remain = userInput - serviceCharge;
        tvServiceCharge.setText(serviceCharge + "");
        tvRemain.setText(remain + "");

    }

    @Override
    public void onTransferOpenTransferFail(Exception e) {
        super.onTransferOpenTransferFail(e);
    }

    @Override
    public void onTransferTransferSuccess(String resp) {
        super.onTransferTransferSuccess(resp);
        ToastUtil.getInstance().shortLength(context, "提币成功");
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onTransferTransferFail(Exception e) {
        super.onTransferTransferFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }

    @Override
    public void onTransferRechargeSuccess(String resp) {
        super.onTransferRechargeSuccess(resp);
        //获取自己的充币地址
//        etAddress.setText(resp);
    }

    @Override
    public void onTransferRechargeFail(Exception e) {
        super.onTransferRechargeFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE_WITH_DEFAULT_SCAN) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    etAddress.setText(result + "");
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.getInstance().shortLength(context, "解析二维码失败");
                }
            }
        }
    }
}
